package com.jrx.anytxn.customer.controller;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.dto.customer.LimitAdjustSummary;
import com.jrx.anytxn.customer.dto.customer.TlBatchAdjustLimitRes;
import com.jrx.anytxn.customer.service.IAdjustListSummaryService;
import com.jrx.anytxn.customer.util.ExcelUtil;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;

@Api(tags = "批量调额汇总")
@RestController
@RequestMapping("/customer/adjustLimitSummary")
public class AdjustLimitSummaryController {

    private static final Logger logger= LoggerFactory.getLogger(AdjustLimitSummaryController.class);

    @Autowired
    private InfoService infoService;
    @Autowired
    private IAdjustListSummaryService adjustListSummaryService;

    @ApiOperation(value = "分页查询批量调额汇总信息", notes = "分页查询批量调额汇总信息")
    @GetMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = true)})
    public TxnRespResult<TxnPage<TlBatchAdjustLimitRes>> getAllPageByTenId(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        TxnRespResult<TxnPage<TlBatchAdjustLimitRes>> result = new TxnRespResult<>();
        TxnPage<TlBatchAdjustLimitRes> response;
        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            response = adjustListSummaryService.findAllPageByTenantId(pageNum, pageSize, tenantId);
            result.getSuccess(response);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "下载批量调额汇总信息文件", notes = "下载批量调额汇总信息文件")
    @GetMapping(value = "/downLoad")
    public void downLoadCoupon(HttpServletResponse response, @RequestParam("batchId") String batchId,
                               @RequestParam String tenantId,@RequestParam String fileName) throws TxnBizException {
        logger.info("下载批量调额汇总信息文件，batchId：{}", batchId);

        //生成汇总数据
        List<LimitAdjustSummary> summaryList = adjustListSummaryService.createExcelMessage(batchId,tenantId,fileName);

        String[] title = {"客户ID","客户姓名","证件号","手机号","调额时间","调额方式","调整前额度","调整后额度","文件名","调额结果","操作员"};

        String downFile = "LimitAdjustSummary.xls";

        String sheetName = "LimitAdjustSummary";

        String [][] content = new String[summaryList.size()][];
        for (int i = 0; i < summaryList.size(); i++) {
            content[i] = new String[title.length];
            LimitAdjustSummary limitAdjustSummary = summaryList.get(i);
            content[i][0] = limitAdjustSummary.getCustomerId();
            content[i][1] = limitAdjustSummary.getChineseName();
            content[i][2] = limitAdjustSummary.getIdNumber();
            content[i][3] = limitAdjustSummary.getMobile();
            content[i][4] = DateUtils.format(limitAdjustSummary.getCreateTime(),DateUtils.DATETIME_PATTERN);
            content[i][5] = limitAdjustSummary.getAdjustType();
            content[i][6] = limitAdjustSummary.getLimitPermBefore().toString();
            content[i][7] = limitAdjustSummary.getLimitPermAfter().toString();
            content[i][8] = limitAdjustSummary.getFileName();
            content[i][9] = limitAdjustSummary.getResult();
            content[i][10] = limitAdjustSummary.getUpdateBy();
        }

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ downFile);
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        try (OutputStream outputStream = response.getOutputStream()){
            wb.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            logger.error("下载批量调额汇总文件异常", e);
        }
    }
}
